package guijavacommander.actions;

import guijavacommander.JavaCommander;
import guijavacommander.FilePanel;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.DataInputStream;
import java.io.DataInput;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * User: Deady
 * Date: 16.07.2009
 * Time: 13:08:31
 */
public class CopyGnomeAction extends AbstractAction {

    private Log logger = LogFactory.getLog(CopyGnomeAction.class);


    public void actionPerformed(ActionEvent e) {
        JavaCommander cmd = JavaCommander.instance;
        FilePanel active = cmd.getActivePanel();
        FilePanel inactive = cmd.getInactivePanel();

        File[] selected = active.getSelectedFiles();
        File dest = inactive.getCurrentFolder();

        if (JOptionPane.showConfirmDialog(cmd, "Copy "+selected.length+" files to "+dest+"?",
                "Attention", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {

            StringBuilder sb = new StringBuilder("cp ");
            for (File f : selected) {
                sb.append("\"").append(f.getAbsolutePath()).append("\" ");
            }
            sb.append(dest.getAbsolutePath()).append(" ");
            sb.append(" | zenity --progress --pulsate --auto-close --text=Copy");

            logger.debug("Copy: "+sb.toString());
            try{
                Process process = Runtime.getRuntime().exec(new String[] {
                        "/bin/bash",
                        "-c",
                        sb.toString()
                });
                //Process process = Runtime.getRuntime().exec(sb.toString());
                process.waitFor();
                int s = process.exitValue();
                if (s!=0) {
                    DataInput in = new DataInputStream(process.getErrorStream());
                    String errorLine;
                    while ((errorLine = in.readLine())!=null) {
                        logger.debug(errorLine);
                    }
                }
                process.getInputStream().close();
                process.getOutputStream().close();
                process.getErrorStream().close();
            }
            catch (Exception ex){
                ex.printStackTrace();
            }

        }

        active.refresh();
        inactive.refresh();

    }


}
